package com.pine.dcts.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Slf4j
public class ZipUtils {
    /**
     * 解压zip文件
     *
     * @return true/false
     */
    public static boolean unZip(File zipFile, String descDir) {
        boolean flag = false;
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zip = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            // 指定编码，否则压缩包里面不能有中文目录
            zip = new ZipFile(zipFile, Charset.forName("gbk"));
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                 in = zip.getInputStream(entry);

               String outPath =  StringUtils.join(new
                        String[]{descDir, zipEntryName}, File.separator);
               if(entry.isDirectory()){
                   // 判断路径是否存在,不存在则创建文件路径
                   File file = new File(outPath);
                   if (!file.exists()) {
                       file.mkdirs();
                   }
               }
                // 判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath);
                // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (file.exists()||file.isDirectory()) {
                    continue;
                }
                 out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[2048];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
            }
            flag = true;
        } catch (IOException e) {
          log.error("解压文件错误",e);
        }finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        return flag;
    }
}
